// 已登录
let denglu = document.querySelector('#login');
let login = getCookie('login');
login ? denglu.innerHTML = "，" + login : '';
denglu.onclick = function () {
    location.href = '../html/login.html';
    localStorage.setItem('url',location.href);
    return;
}
if (!login) {
    location.href = '../html/login.html';
}

// 跳转到购物车
$('.car').click(function () {
    if (!login) {
        alert('请先登录，在2s后跳转到登录界面');
        setTimeout(() => {
             location.href = '../html/login.html';
        }, 1000);
        console.log(login);
        return;
    } else {
        location.href = '../html/mycar.html';
    }
});


let carbody = document.querySelector('.carbody');
let carul = document.querySelector('.carul');
let cartotalnumber = document.querySelector('.cartotalnumber');
let choosenumber = document.querySelector('.choosenumber');
let cartotalprice = document.querySelector('.cartotalprice');
let allcheck = document.querySelector('.allcheck');
let carlist = document.querySelector('.carlist');



async function getcarbody() {
    let res = await pAjax({
        url: '../../6.3getCar.php',
        data: {
            username:login,
        }
    });
    // res = JSON.parse(res);
    localStorage.setItem('data', res);
    
    // console.log(r);
    Rundercardata();
}

getcarbody();
function Rundercardata() {
    // console.log(data);
    let data = localStorage.getItem('data');
    data = JSON.parse(data);
    console.log(data);
    if (data.length == 0) {
        carbody.innerHTML = `
        <div class="carempty">
                <p>你的购物车还是空的！</p>
                <i class='gotobuynow'>马上去购物</i>
            </div> 
        `;
        return;
    }

    let str = '';
    data.forEach(item => {
        // console.log(item);
        singleprice = (item.goods_price * item.cart_number).toFixed(2);
        // console.log(singleprice );
        str += `
    <li>
        <input type="checkbox" idx='${item.goods_id}' ${item.is_select==1? 'checked':''} class='singlecheck'>
        <img src="${item.goods_small_logo}" alt="">
        <span>${item.goods_name}</span>
        <i>${item.goods_price}元</i>
        <i><b class="down" idx='${item.goods_id}'>-</b><em>${item.cart_number}</em><b class="up" idx='${item.goods_id}'>+</b></i>
        <i>${singleprice}元</i>
        <i idx='${item.goods_id}' class='delcardata'>x</i>
    </li>
        `;
    });

    // 修改最底部的值
    carul.innerHTML = str;
    cartotalnumber.innerHTML = data.length;
    let single=data.filter(item => {
        return item.is_select == '1';
    });
    choosenumber.innerHTML = single.length;
    let totalprice = 0;
    single.forEach(item => {
        totalprice += item.cart_number * item.goods_price;
    });
    cartotalprice.innerHTML = `合计：${totalprice.toFixed(2)}元`;
}

carbody.onclick = function (e) {
    let target = e.target;

    // 没有商品的时候
    if (target.className == 'gotobuynow') {
        location.href = '../html/list.html';
    }

    // 有商品的时候
    // 全选
    if (target.className == 'allcheck') {
        let data = localStorage.getItem('data');
        data = JSON.parse(data);
        data.forEach(item => {
            target.checked ? item.is_select = '1' : item.is_select = '0';
        });
        // 更改之后要更改localStorage的值
        localStorage.setItem('data', JSON.stringify(data));
        Rundercardata();
        return;
    }
    
    // 单选
    if (target.className == 'singlecheck') {
        let data = localStorage.getItem('data');
        data = JSON.parse(data);
        let id = target.getAttribute('idx');
        // console.log(id);
        data.forEach(item => {
            if (item.goods_id == id) {
                target.checked ? item.is_select = '1' : item.is_select = '0';
            }    
        });
        let flag;
        flag=data.every(item => {
            return item.is_select == '1';
        });
        allcheck.checked = flag;
        // 更改之后要更改localStorage的值
        localStorage.setItem('data', JSON.stringify(data));
        Rundercardata();
        return;
    }


    // 增加商品数量
    if (target.className == 'up') {
        let goodnumber = target.previousElementSibling.innerText * 1;
        let goodid = target.getAttribute('idx');
        // console.log(goodid);
        goodnumber++;
        goodnumberUpdate(goodid,goodnumber);
        return;
    }


    // 减少商品数量
    if (target.className == 'down') {
        let goodnumber = target.nextElementSibling.innerText * 1;
        let goodid = target.getAttribute('idx');
        // console.log(goodid);
        if (goodnumber == 0) {
            confirm('不能在减少了');
            // goodnumberUpdate(goodid, goodnumber);
            return;
        }
        goodnumber--;
        goodnumberUpdate(goodid,goodnumber);
        return;
    }


    // 删除商品
    if (target.className == 'delcardata') {
        let goodid = target.getAttribute('idx');
        let flag = confirm('是否确认删除该商品?');
        if (!flag) {
            return;
        }
        delcardatas(goodid);
        return;
    }

    // 结算
    if (target.className == 'settlement') {
        let data = localStorage.getItem('data');
        data = JSON.parse(data);
        let flag = data.some(item => {
            return item.is_select == '1';
        });
        if (!flag) {
            confirm('请选择商品');
            return;
        }
        location.href = '../html/buy.html';
    }
}


// 商品数量的+ - 
async function goodnumberUpdate(id, num) {
    let data = localStorage.getItem('data');
    data = JSON.parse(data);
    let res = await pAjax({
        url: '../../6.7Updata.php',
        data: {
            username:login,
            goods_id: id,
            goods_num:num,
        }
    });
    res = JSON.parse(res);
    // console.log(res);
    if (res.code) {
        data.forEach(item => {
            item.cart_number=item.goods_id == id ? num : item.cart_number;
        });
        localStorage.setItem('data',JSON.stringify(data));
        Rundercardata();
    }
}

// 删除商品
async function delcardatas(id) {
    let data = localStorage.getItem('data');
    data = JSON.parse(data);
    let res = await pAjax({
        url: '../../6.4removeCar.php',
        data: {
            username: login,
            goods_id:id,
        }
    });
    res = JSON.parse(res);
    console.log(res);
    if (res.code) { 
        data = data.filter(item => {
            return item.goods_id != id;
        });
        localStorage.setItem('data',JSON.stringify(data));
        Rundercardata();
    }
    
}
